package com.jf.identity.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 加载本地machine.config
 *
 * @author FCG
 */
public class MachineConfigLoader {

    private final static String machineConfigDir = "C:\\Windows\\JFS\\Machine.Config";
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 读取本地xml文件，装载系统配置
     *
     * @return 系统配置
     */
    @SuppressWarnings("unchecked")
    public MachineConfig load() {
        File file = new File(machineConfigDir);
        if (!file.exists()) {
            logger.error("Machine.Config文件不存在");
            throw new RuntimeException("Machine.Config文件不存在");
        }
        if (!file.canRead()) {
            logger.error("不具备权限读取Machine.Config文件");
            throw new RuntimeException("不具备权限读取Machine.Config文件");
        }
        SAXReader reader = new SAXReader();
        MachineConfig machineConfig = new MachineConfig();
        try {
            Document document = reader.read(file);
            Element root = document.getRootElement();
            for (Iterator<Element> ite = root.elementIterator(); ite.hasNext(); ) {
                Element element = ite.next();
                if ("AppSettings".equalsIgnoreCase(element.getName())) {
                    setMachineConfig(machineConfig, element);
                }
            }
        } catch (DocumentException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return machineConfig;
    }

    private void setMachineConfig(MachineConfig machineConfig, Element element) {
        Map<String, String> map = childElementToMap(element);
        String url = map.get("JDM-mysql-url".toUpperCase());
        isAnyBlank( url);
        machineConfig.setDbConnectionUrl(url);
    }

    /**
     * 将<add key="xxx" value="xxx"/>此类格式的元素转换成map
     *
     * @param parentElement 父元素
     * @return 子元素map
     */
    @SuppressWarnings("unchecked")
    private Map<String, String> childElementToMap(Element parentElement) {
        Map<String, String> childElementMap = new HashMap<>(16);
        for (Iterator<Element> iterator = parentElement.elementIterator(); iterator.hasNext(); ) {
            Element child = iterator.next();
            //子元素格式：<add key="IS-OPENAPI-GET-URL" value="http://10.0.2.167:83/openapi/action"/>
            //将属性"key"对应的值，统一转换成为大写，再存入map
            childElementMap.put(child.attributeValue("key").toUpperCase(), child.attributeValue("value"));
        }
        return childElementMap;
    }

    /**
     * 验证是否得到需要的配置信息
     *
     * @param args 待验证的参数
     */
    private void isAnyBlank(String... args) {
        if (args.length == 0) {
            return;
        }
        boolean blank = true;
        for (String arg : args) {
            blank = true;
            if (arg == null) {
                break;
            }
            for (int i = 0; i < arg.length(); i++) {
                if (!Character.isWhitespace(arg.charAt(i))) {
                    blank = false;
                    break;
                }
            }
            if (blank) {
                break;
            }
        }
        if (blank) {
            logger.error("解析Machine.Config文件失败");
            throw new RuntimeException("解析Machine.Config文件失败");
        }
    }

}






















